package com.jwtproject.bootserver.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jwtproject.bootserver.security.filter.CustomLoginAuthenticationFilter;
import com.jwtproject.bootserver.security.handler.SecurityAccessDeniedHandler;
import com.jwtproject.bootserver.security.handler.SecurityAuthenticationEntryPointHandler;
import com.jwtproject.bootserver.security.handler.SecurityAuthenticationFailureHandler;
import com.jwtproject.bootserver.security.handler.SecurityAuthenticationSuccessHandler;
import com.jwtproject.bootserver.security.provider.MyUsernameAuthenticationProvider;
import com.jwtproject.bootserver.security.service.MyUsernameDetailsService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private ClientDetailsService clientDetailsService;
    @Lazy
    @Autowired
    private AuthorizationServerTokenServices defaultAuthorizationServerTokenServices;


    @Resource
    private SecurityAccessDeniedHandler securityAccessDeniedHandler;

    @Resource
    private SecurityAuthenticationEntryPointHandler securityAuthenticationEntryPointHandler;


    @Resource
    private MyUsernameDetailsService myUsernameDetailsService;

    // 指定密码的加密方式
    @SuppressWarnings("deprecation")
    @Bean
    PasswordEncoder passwordEncoder(){
        // 不对密码进行加密
        return NoOpPasswordEncoder.getInstance();
    }

    // 配置用户及其对应的角色
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(empUsernameAuthenticationProvider());
    }


    // 配置 URL 访问权限
    @Override
    protected  void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setSecurityMetadataSource(cfisms());
                        object.setAccessDecisionManager(cadm());
                        return object;
                    }
                })
                .and()
                .exceptionHandling()
                // 认证配置当用户请求了一个受保护的资源，但是用户没有通过登录认证，则抛出登录认证异常，SecurityAuthenticationEntryPointHandler类中commence()就会调用
                .authenticationEntryPoint(securityAuthenticationEntryPointHandler)
                //用户已经通过了登录认证，在访问一个受保护的资源，但是权限不够，则抛出授权异常，SecurityAccessDeniedHandler类中handle()就会调用
                .accessDeniedHandler(securityAccessDeniedHandler)
                .and().formLogin().loginProcessingUrl("/login").permitAll()//开启表单登录并配置登录接口
                .and().
                addFilterAt(getCustomLoginAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                .csrf().disable(); // 关闭csrf
    }

    //动态配置权限
    @Bean
    CustomFilterInvocationSecurityMetadataSource cfisms() {
        return new CustomFilterInvocationSecurityMetadataSource();
    }

    //角色信息的对比
    @Bean
    CustomAccessDecisionManager cadm() {
        return new CustomAccessDecisionManager();
    }



    @Bean
    public MyUsernameAuthenticationProvider empUsernameAuthenticationProvider(){
        MyUsernameAuthenticationProvider provider = new MyUsernameAuthenticationProvider(myUsernameDetailsService, passwordEncoder());
        // 禁止隐藏用户未找到异常
        provider.setHideUserNotFoundExceptions(false);
        return provider;
    }

    @Bean
    public CustomLoginAuthenticationFilter getCustomLoginAuthenticationFilter() {
        CustomLoginAuthenticationFilter filter = new CustomLoginAuthenticationFilter();
        try {
            filter.setAuthenticationManager(this.authenticationManagerBean());
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 设置登陆成功处理
        filter.setAuthenticationSuccessHandler(LoginSuccessHandler());
        //filter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler("/login?error"));
        // 设置权限验证失败处理
        filter.setAuthenticationFailureHandler(AuthenticationFailureHandler());
        return filter;
    }


    @Bean
    public AuthenticationSuccessHandler LoginSuccessHandler() {
        return SecurityAuthenticationSuccessHandler.builder()
                .objectMapper(objectMapper)
                .clientDetailsService(clientDetailsService)
                .passwordEncoder(passwordEncoder())
                .defaultAuthorizationServerTokenServices(defaultAuthorizationServerTokenServices).build();
    }

    @Bean
    public SecurityAuthenticationFailureHandler AuthenticationFailureHandler() {
        return new SecurityAuthenticationFailureHandler();
    }

    @Bean
    @Override
    @SneakyThrows
    public AuthenticationManager authenticationManagerBean() {
        return super.authenticationManagerBean();
    }
}
